package com.mozz.finally_work.servlet;

import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.pojo.Blog;
import com.mozz.finally_work.pojo.Category;
import com.mozz.finally_work.pojo.Tag;
import com.mozz.finally_work.utils.MybatisUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "HandleUpdateBlogServlet", value = "/HandleUpdateBlogServlet")
public class HandleUpdateBlogServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SqlSession session = MybatisUtils.getSession();
        BlogDao dao = session.getMapper(BlogDao.class);

        // 图片上传
        // 使用fileupload组件完成文件上传
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/cover");
        // 判断，该路径是否存在
        File file = new File(path);
        if(!file.exists()){
            // 创建该文件夹
            file.mkdirs();
        }

        // 解析request对象，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String filename = null;
        String title = null;
        String content = null;
        String blogId = null;
        List<Tag> tags = new ArrayList<>();
        List<Category> categories = new ArrayList<>();
        // 解析request
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
            // 遍历
            for(FileItem item:items){
                // 进行判断，当前item对象是否是上传文件项
                if(item.isFormField()){
                    // 说明普通表单
                    String fieldName = item.getFieldName();
                    if (item.getString("UTF-8") == null || item.getString("UTF-8").trim().equals("")) {
                        response.sendRedirect("index.jsp");
                        return;
                    }
                    System.out.println(fieldName);
                    if (fieldName.equals("title")) {
                        title = item.getString("UTF-8");
                    } else if (fieldName.equals("content")) {
                        content = item.getString("UTF-8");
                    } else if (fieldName.equals("blogId")) {
                        blogId = item.getString("UTF-8");
                    }else if (fieldName.equals("tags")) {
                        Tag tag = new Tag();
                        tag.setId(item.getString("UTF-8"));
                        tags.add(tag);
                    }   else if (fieldName.equals("category")) {
                        Category category = new Category();
                        category.setId(item.getString("UTF-8"));
                        categories.add(category);
                    }

                }else{
                    // 说明上传文件项
                    // 获取上传文件的名称
                    filename = item.getName();
                    if (!filename.equals("")) {
                        // 把文件的名称设置唯一值，uuid
                        String coverUuid = UUID.randomUUID().toString().replace("-", "");
                        filename = coverUuid+"_"+filename;
                        // 完成文件上传
                        item.write(new File(path,filename));
                        // 删除临时文件
                        item.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 构建对象
        // 生成UUID


        Blog blog = new Blog();
        blog.setId(blogId);
        blog.setTitle(title);
        blog.setContent(content);
        blog.setPublicTime(new Date());
        if (!filename.equals("")) {
            blog.setCover(filename);
        }
        System.out.println(blog);

//         使用dao更新记录
        Integer result = dao.updateBlog(blog);
        session.commit();


        // 如果有tag，添加tag映射
        if (tags.size() > 0) {
            for (Tag tag : tags) {
                Integer ret = dao.addBlogTag(UUID.randomUUID().toString(), blog.getId(), tag.getId());
                session.commit();
            }
        }

        // 如果有tag，添加tag映射
        if (categories.size() > 0) {
            for (Category category : categories) {
                Integer ret = dao.addBlogCategory(UUID.randomUUID().toString(), blog.getId(), category.getId());
                session.commit();
            }
        }

        session.close();
        response.sendRedirect("index.jsp");

    }
}
